<?php

class PageUrlRule extends CBaseUrlRule
{

    public $findInDb = array();
    public $parseType = 'page';
    protected $activePage;
    protected $activeTableName = '';
    protected $activeControllerName = '';

    protected function findUrlInDb($url)
    {

        if (!empty($this->findInDb)) {
            $db = Yii::app()->db;
            $counter = 0;
            
            /*
             * Пересмотреть способ поиска урл без цикла. Определять по ервому
             * параметру урл есть ли он в массиве.
             */
            
            foreach ($this->findInDb as $key => $value) {
                $sql = "SELECT * FROM `$value` WHERE `href`='$url' LIMIT 1";

                $controllerName = $key;
                if (is_numeric($key)) {
                    $controllerName = $value;
                }


                $urlDb = $db->createCommand($sql);
               
                if (($val = $urlDb->queryRow())) {
                    if ($counter == 0) {

                        $this->activeControllerName = Yii::app()->defaultController;
                    } else {
                        $this->activeControllerName = $controllerName;
                    }

                    $this->activeTableName = $value;
                    $this->activePage = $val;
                   
                    return true;
                }
                $counter++;
            } 


            //   $this->activePage = $urlDb->getFrom();
            // $this->activePage = $urlDb->queryRow();
        }
        
        return false;
    }

    protected function testUrl($urlArray)
    {
        $levelLength = count($urlArray);
        $db = Yii::app()->db
                ->createCommand()
                ->select('p' . ($levelLength - 1) . '.id');
        $tables = array();
        $whereString = '';

        for ($i = 0, $f = 1; $i < $levelLength; $i++, $f++) {
            $tables[] = $this->activeTableName . '  p' . $i;
            if ($i > 0) {
                $whereString .= ' AND ';
            }

            $whereString .= "`p$i`.`href`='" . ($urlArray[$i]) . "'";

            if ($levelLength == $f) {
                // $whereString .= " AND `p$i`.`level`=0";
            } else {
                $whereString .= " AND `p$i`.`id`=`p$f`.`parent_id`";
            }
        }


        $db->from($tables);
        $db->where($whereString);
      
        return $db->queryRow();
    }

    public function createUrl($manager, $route, $params, $ampersand)
    {

        return $route;
        if (isset($parans['catalog'])) {
            return $route;
        } else {
            return 'site/index';
        }
        return false;  // правило не подошло
    }

    public function parseUrl($manager, $request, $pathInfo, $rawPathInfo)
    {


        $urlArray = explode('/', $pathInfo);
        if ($this->findUrlInDb(end($urlArray))) { // Ищем по таблицам урл
            
            if ($this->parseType == 'page') {

                if (count($urlArray) > 1) {
                    return $pathInfo;
                }

                Yii::app()->urlManager->addRules(array(
                    '<controller:\w+>' . $this->activeControllerName . '/index' => '<controller>/'
                ));
                return $this->activeControllerName . '/index';
            } elseif (isset($urlArray[0]) && !empty($urlArray[0])) {

                if ($this->testUrl($urlArray)) {
                    return $this->activeControllerName . '/index';
                }
            }
        }

        return $pathInfo;
    }

}